<?php
/**
 * User: hjd-yao
 * Date: 2019/6/17
 * Time: 15:56
 */

namespace Shop\Http\Controllers\Wap;


use App\Helpers\SelfResponse;
use App\Models\User\AccountFlowModel;
use App\Models\User\RechargeRecordModel;
use App\Models\User\TfRecordModel;
use App\Models\User\WdModel;
use DC\UserCenter\Models\UserAuthModel;
use Develop\Models\ConfigModel;
use Illuminate\Validation\Rule;
use DC\UserCenter\Models\UserInfoModel;
use DC\UserCenter\Models\UserWalletModel;
use Illuminate\Http\Request;
use Shop\Http\Controllers\BaseController;
use Yansongda\Pay\Pay;


class AccountController extends BaseController
{
    public function rgRecord(Request $request)
    {
        $user_id = $request->input('user_id');
        $pageNum = $request->input('page_num',1);

        $list = RechargeRecordModel::where('user_id',$user_id)->orderBy('created_at','desc')->forPage($pageNum,$this->perNum())->get();
        return $this->wapRender('account.rg_record',[
            'page_title'=>'充值记录',
            'list'=>$list
        ]);
    }

    public function rgApply(Request $request)
    {
        if($request->isMethod('post')){
            $validatedData = $request->validate([
                'money'=>'required|numeric|between:1,1000000',
                'remark'=>'nullable|text_rule',
            ],[
                'required'=>':attribute不能为空',
                'text_rule'=>':attribute存在非法字符',
                'numeric'=>':attribute必须是数字',
                'between'=>':attribute只能在:min和:max之间',
                'url'=>':attribute凭证地址无效',
            ],[
                'money'=>'充值金额',
                'remark'=>'备注',
            ]);

            if(!config('website')['controller_recharge']){
                return SelfResponse::error('充值功能已关闭');
            }

            if(config('website')['is_need_revoucher']){
                if(!$request->input('voucher') || empty($request->input('voucher'))){
                    return SelfResponse::error('汇款凭证不能为空');
                }
            }

            if(!$request->input('pay_type') || empty($request->input('pay_type'))){
                return SelfResponse::error('请选择充值币种');
            }


            if($validatedData['money'] < get_rule('rg_min')){
                return SelfResponse::error('最低充值金额为'.get_rule('rg_min').'元');
            }

            if(($validatedData['money'] % get_rule('rg_mul')) !=0 ){
                return SelfResponse::error('充值金额必须为'.get_rule('rg_mul').'的整数倍');
            }

            $post_data=$request->all();

            $rgModel = new RechargeRecordModel();
            if(!$rgModel->apply($post_data)){
                return SelfResponse::error($rgModel->getErrorMsg('申请失败,请稍后再试'));
            }
            return SelfResponse::success('申请成功','f_Wap_Account_rgRecord');
        }else{

            return $this->wapRender('account.rg_apply',[
                'page_title'=>'充值',
                'company_account'=> array_map(function ($val){
                    return str2arr($val,'-');
                },config('website.company_account')),
            ]);
        }
    }



    public function rgDetail()
    {

    }

    public function onlinergApply(Request $request){
        if($request->isMethod('post')){

            if(!config('website')['controller_recharge']){
                return SelfResponse::error('充值功能已关闭');
            }
            $money = $request->input('money');

            if($money < get_rule('gw_award3')){
                return SelfResponse::error('最低充值金额为'.get_rule('gw_award3').'元');
            }

            if(($money % get_rule('sign_in_keep_day')) !=0 ){
                return SelfResponse::error('充值金额必须为'.get_rule('sign_in_keep_day').'的整数倍');
            }

            $rgModel = new RechargeRecordModel();
            $rg_id = $rgModel->apply($request->input());
            $rg_sn = $rgModel->where('id',$rg_id)->value('rg_sn');

            $aliPayOrder = [
                'out_trade_no' => $rg_sn,
                'total_amount' => $money, // 支付金额
                'subject'      => '支付宝手机网页支付' // 备注
            ];

            $config = config('pay.alipay');

            $config['return_url'] = $config['return_url'].'?out_trade_no='.$rg_sn;

            $config['notify_url'] = $config['notify_url'].'?out_trade_no='.$rg_sn;

            $result = Pay::alipay($config)->wap($aliPayOrder);

            return $result ;
        }
    }

    public function wdRecord(Request $request)
    {
        $user_id = $request->input('user_id');
        $pageNum = $request->input('page_num',1);
        $list = WdModel::where('user_id',$user_id)->orderByRaw('case when status <0 then 100 else 0 end asc,status asc')->forPage($pageNum,$this->perNum())->get();
        return $this->wapRender('account.wd_record',[
            'page_title'=>'提现记录',
            'list'=>$list,
        ]);
    }

    public function wdApply(Request $request)
    {
        $user_id = $request->input('user_id');
        $wallet = UserWalletModel::find($user_id);
        if($request->isMethod('post')){
            $validatedData = $request->validate([
                'money'=>'required|numeric|between:1,'.$wallet->money2,
                'remark'=>'nullable|text_rule',
                'pay_type'=>['required',Rule::in([1,2,3])],
            ],[
                'required'=>':attribute不能为空',
                'text_rule'=>':attribute存在非法字符',
                'numeric'=>':attribute必须是数字',
                'between'=>':attribute只能在:min和:max之间',
                'in'=>':attribute不存在',
            ],[
                'money'=>'提现金额',
                'remark'=>'备注',
                'pay_type'=>'收款方式',
            ]);

            $rule_wd_time = str2arr(json_decode(get_rule('wd_time')),'-');

            $start_time=strtotime(date("Y-m-d")." ".$rule_wd_time[0]);
            $end_time=strtotime(date("Y-m-d")." ".$rule_wd_time[1]);

            if(time()<$start_time || time() > $end_time){
                return SelfResponse::apiError('提现时间为早上'.$rule_wd_time[0].'点到下午'.$rule_wd_time[1].'点之间,其他时间段不允许提现');
            }

            $pay_type =$validatedData['pay_type'];

            $info = UserInfoModel::find($user_id);
            if($pay_type==1&&!$info->alipay){
                return SelfResponse::error('你没有完善支付宝信息');
            }
            if($pay_type==2&&!$info->weichat){
                return SelfResponse::error('你没有完善微信信息');
            }
            if($pay_type==3&&!$info->bank_card){
                return SelfResponse::error('你没有完善银行卡信息');
            }

            if($validatedData['money'] < get_rule('wd_min') || $validatedData['money'] > get_rule('wd_max') ){
                return SelfResponse::error('最低提现金额为'.get_rule('wd_min').'元,最大提现金额为'.get_rule('wd_max').'元');
            }

            if(($validatedData['money'] % get_rule('wd_mul')) !=0 ){
                return SelfResponse::error('提现金额必须为'.get_rule('wd_mul').'的整数倍');
            }

            if($wallet->money2-$validatedData['money']<0){
                return SelfResponse::error('提现金额超出账户余额');
            }
            $wd = new WdModel();
            if(!$wd->apply($validatedData)){
                return SelfResponse::error($wd->getErrorMsg('提现失败'));
            }
            return SelfResponse::success('提现成功','f_Wap_Account_wdRecord');
        }else{
            return $this->wapRender('account.wd_apply',[
                'page_title'=>'提现',
                'wallet'=>$wallet,
                'info'=>UserInfoModel::find($user_id),
            ]);
        }
    }

    public function wdDetail()
    {

    }


    // 转账
    public function transfer(Request $request){
        $user_id = $request->input('user_id');
        $wallet = UserWalletModel::find($user_id);

        $min_tf=get_rule('tf_min');
        $mul_tf=get_rule('tf_mul');
        $max_tf=get_rule('tf_max');

        if($request->isMethod('post')){

            $type = $request->input('in_or_out');
            $pay_type = $request->input('pay_type');
            if(!$pay_type || empty($pay_type)){
                return SelfResponse::error('请选择转换或转账类型');
            }
            if($type=='in'){
                $validatedData = $request->validate([
                    'money'=>'required|numeric|between:1,99999999999',
                    'comment'=>'nullable|text_rule',
                ],[
                    'required'=>':attribute不能为空',
                    'text_rule'=>':attribute存在非法字符',
                    'numeric'=>':attribute必须是数字',
                    'between'=>':attribute只能在:min和:max之间',
                ],[
                    'money'=>'转换金额',
                    'comment'=>'备注',
                ]);

                $out_field = 'money2' ;

                if($wallet->$out_field-$validatedData['money']<0){
                    return SelfResponse::error('账户余额不足,无法完成转换');
                }

                if($min_tf-$validatedData['money']>0){
                    return SelfResponse::error('转账金额不能小于'.$min_tf);
                }
                if($max_tf-$validatedData['money']<0){
                    return SelfResponse::error('转账金额不能大于'.$max_tf);
                }
                if($validatedData['money']%$mul_tf!=0){
                    return SelfResponse::error('转账金额必须为'.$mul_tf.'的整数倍');
                }

                if(!config('website')['transfer_in']){
                    return SelfResponse::error('币种转换功能已关闭');
                }

                $post_data=$request->all();

                $tfModel = new TfRecordModel();
                if(!$tfModel->tfRecordIn($post_data)){
                    return SelfResponse::error($tfModel->getErrorMsg('转换失败'));
                }
                return SelfResponse::success('转换成功','f_Wap_Account_tfRecord');

            }else{

                $validatedData = $request->validate([
                    'to_number'=>'required',
                    'money'=>'required|numeric|between:1,9999999999',
                    'comment'=>'nullable|text_rule',
                ],[
                    'required'=>':attribute不能为空',
                    'text_rule'=>':attribute存在非法字符',
                    'numeric'=>':attribute必须是数字',
                    'between'=>':attribute只能在:min和:max之间',
                ],[
                    'to_number'=>'转入账号',
                    'money'=>'提现金额',
                    'comment'=>'备注',
                ]);


                switch ($pay_type){
                    case '101':
                        $out_field = 'money1' ;
                        break;
                    case '202':
                        $out_field = 'money2' ;
                        break;
                    case '404':
                        $out_field = 'money4' ;
                        break;
                    default:
                        return SelfResponse::error('转换类型错误'.$pay_type);
                        break;
                }
                $pay_pwd = $request->input('password_safe');
                if($pay_pwd == '' || empty($pay_pwd)){
                    return SelfResponse::error('支付密码不能为空');
                }
                if(! UserAuthModel::init()->checkSafePwd($pay_pwd,$user_id)){
                    return SelfResponse::error('支付密码输入错误');
                }
                if($wallet->$out_field-$validatedData['money']<0){
                    return SelfResponse::error('账户余额不足,无法完成转账');
                }
                if($min_tf-$validatedData['money']>0){
                    return SelfResponse::error('转账金额不能小于'.$min_tf);
                }
                if($max_tf-$validatedData['money']<0){
                    return SelfResponse::error('转账金额不能大于'.$max_tf);
                }
                if($validatedData['money']%$mul_tf!=0){
                    return SelfResponse::error('转账金额必须为'.$mul_tf.'的整数倍');
                }

                if(!config('website')['transfer_out']){
                    return SelfResponse::error('转账功能已关闭');
                }
                $post_data=$request->all();
                $obi = new TfRecordModel();
                if(!$obi->tfRecordOut($post_data)){
                    return SelfResponse::error($obi->getErrorMsg('转账失败'));
                }
                return SelfResponse::success('转账成功','f_Wap_Account_tfRecord');
            }

        }else{
            return $this->wapRender('account.transfer',[
                'page_title'=>'转账',
                'wallet'=>$wallet,
                'info'=>UserInfoModel::find($user_id),
            ]);
        }
    }

    public function tfRecord(Request $request)
    {
        $user_id = $request->input('user_id');
        $pageNum = $request->input('page_num',1);
        $list = TfRecordModel::with('to_users')->where('out_uid',$user_id)->orderBy('created_at','desc')->forPage($pageNum,$this->perNum())->get();
        return $this->wapRender('account.tf_record',[
            'page_title'=>'转账记录',
            'list'=>$list,
        ]);
    }

}